package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RateLimiter;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ConvertUtil;
import com.ruoyi.common.utils.PageInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.Info;
import com.ruoyi.system.domain.InfoCustom;
import com.ruoyi.system.service.IInfoCategoryInfoService;
import com.ruoyi.system.service.IInfoCategoryService;
import com.ruoyi.system.service.IInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 新闻Controller
 * 
 * @author ruoyi
 * @date 2022-12-02
 */
@Controller
@RequestMapping("/system/info")
public class InfoController extends BaseController
{
    private String prefix = "system/info";

    @Autowired
    private IInfoService infoService;

    @Autowired
    private IInfoCategoryInfoService infoCategoryInfoService;

    @Autowired
    private IInfoCategoryService infoCategoryService;

    @PreAuthorize("@ss.hasPermi('system:info:view')")
    @GetMapping()
    public String info()
    {
        return prefix + "/info";
    }

    /**
     * 查询新闻列表
     */
    /*@RequiresPermissions("system:info:list")*/
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Info info)
    {
        startPage();
        List<Info> list = infoService.selectInfoList(info);
        return getDataTable(list);
    }

    /**
     * 导出新闻列表
     */
    @PreAuthorize("@ss.hasPermi('system:info:export')")
    @Log(title = "新闻", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Info info)
    {
        List<Info> list = infoService.selectInfoList(info);
        ExcelUtil<Info> util = new ExcelUtil<Info>(Info.class);
        return util.exportExcel(list, "新闻数据");
    }

    /**
     * 新增新闻
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存新闻
     */
    @PreAuthorize("@ss.hasPermi('system:info:add')")
    @Log(title = "新闻", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Info info)
    {
        return toAjax(infoService.insertInfo(info));
    }

    /**
     * 修改新闻
     */
    /*@RequiresPermissions("system:info:edit")*/
    @GetMapping("/edit/{infoid}")
    public String edit(@PathVariable("infoid") String infoid, ModelMap mmap)
    {
        Info info = infoService.selectInfoByInfoid(infoid);
        mmap.put("info", info);
        return prefix + "/edit";
    }

    /**
     * 修改保存新闻
     */
   /* @RequiresPermissions("system:info:edit")*/
    @Log(title = "新闻", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Info info)
    {
        return toAjax(infoService.updateInfo(info));
    }

    /**
     * 删除新闻
     */
    /*@RequiresPermissions("system:info:remove")
    @Log(title = "新闻", businessType = BusinessType.DELETE)*/
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(infoService.deleteInfoByInfoids(ids));
    }

    /*@PostMapping("/addcustom")
    @ResponseBody
    public AjaxResult addCustom(@RequestParam("categoryid") String CategoryId, @RequestParam("jianti") String Jianti, @RequestParam("infotitle") String Infotitle,
                                @RequestParam("infotitle2") String Infotitle2, @RequestParam("summary") String Summary, @RequestParam("author") String Author,
                                @RequestParam("infocontent") String Infocontent, @RequestParam("picurl") String Picurl, @RequestParam("returnurl") String Returnurl,
                                @RequestParam("checkpass") int Checkpass, @RequestParam("ordernum") int Ordernum, HttpServletRequest request)
    {
        if(!Usercheck.IsZJZXGuanli(request)){
            error("当前账户非专家管理账户");
        }
        return toAjax(infoService.addCustom(CategoryId,Jianti,Infotitle,Infotitle2,Summary,Author,Infocontent,Picurl,Returnurl,Checkpass,Ordernum));
    }*/

    @Log(title = "添加新闻", businessType = BusinessType.INSERT)
    @PostMapping("/addcustom")
    @ResponseBody
    public AjaxResult addCustom(@Validated @RequestBody InfoCustom infoCustom)
    {
        String CategoryId = infoCustom.getCategoryid() == null ? "":infoCustom.getCategoryid();
        String Jianti = infoCustom.getJianti()== null ? "":infoCustom.getJianti();
        String Infotitle = infoCustom.getInfotitle()== null ? "":infoCustom.getInfotitle();
        String Infotitle2 = infoCustom.getInfotitle2()== null ? "":infoCustom.getInfotitle2();
        String Summary = infoCustom.getSummary()== null ? "":infoCustom.getSummary();
        String Author = infoCustom.getAuthor()== null ? "":infoCustom.getAuthor();
        String Infocontent = infoCustom.getInfocontent()== null ? "":infoCustom.getInfocontent();
        String Picurl = infoCustom.getPicurl()== null ? "":infoCustom.getPicurl();
        String Returnurl = infoCustom.getReturnurl()== null ? "":infoCustom.getReturnurl();
        Date mmAddtime = infoCustom.getAddtime() == null ? new Date():infoCustom.getAddtime();
        Date mmReleasetime = infoCustom.getReleasetime() == null ? new Date("9999-99-99"):infoCustom.getReleasetime();
        long Shifouzhiding = infoCustom.getShifouzhiding()== null ? 0:infoCustom.getShifouzhiding();
        int Checkpass = infoCustom.getCheckpass()== null ? 0:infoCustom.getCheckpass().intValue();

        int num = infoService.getMaxOrdernum(CategoryId);

        int Ordernum = infoCustom.getOrdernum()== null ? num+1:Integer.parseInt(infoCustom.getOrdernum());
        Date Zhidingjieshushijian = infoCustom.getZdjssj()==  null ? new Date():infoCustom.getZdjssj();

        if (Shifouzhiding ==1){
            int Zhidingshuliang = infoService.countZhidingxinwen(CategoryId);

            if (Zhidingshuliang>=3){
                return error("该栏目已存在三条置顶新闻，请修改置顶状态！");
            }
        }

        return toAjax(infoService.addCustom(CategoryId,Jianti,Infotitle,Infotitle2,Summary,Author,Infocontent,Picurl,Returnurl,mmAddtime,mmReleasetime,Shifouzhiding,Zhidingjieshushijian,Checkpass,Ordernum));
    }

   /* @PostMapping("/modifycustom")
    @ResponseBody
    public AjaxResult modifyCustom(@RequestParam("infoid") String InfoId,@RequestParam("oldcategoryid") String OldCategoryId,@RequestParam("newcategoryid") String NewCategoryId,
                                   @RequestParam("jianti") String Jianti,@RequestParam("infotitle") String Infotitle,
                                @RequestParam("infotitle2") String Infotitle2,@RequestParam("summary") String Summary,@RequestParam("author") String Author,
                                @RequestParam("infocontent") String Infocontent,@RequestParam("picurl") String Picurl,@RequestParam("returnurl") String Returnurl,
                                @RequestParam("checkpass") int Checkpass,@RequestParam("ordernum") int Ordernum)
    {
        return toAjax(infoService.modifyCustom(InfoId,OldCategoryId,NewCategoryId,Jianti,Infotitle,Infotitle2,Summary,Author,Infocontent,Picurl,Returnurl,Checkpass,Ordernum));
    }*/

    @Log(title = "修改新闻", businessType = BusinessType.UPDATE)
    @PostMapping("/modifycustom")
    @ResponseBody
    public AjaxResult modifyCustom(@Validated @RequestBody InfoCustom infoCustom)
    {
        String InfoId = infoCustom.getInfoid() == null ? "":infoCustom.getInfoid();
        String OldCategoryId = infoCustom.getOldcategoryid() == null ? "":infoCustom.getOldcategoryid();
        /*String NewCategoryId = infoCustom.getNewcategoryid() == null ? "":infoCustom.getNewcategoryid();*/
        String Jianti = infoCustom.getJianti()== null ? "":infoCustom.getJianti();
        String Infotitle = infoCustom.getInfotitle()== null ? "":infoCustom.getInfotitle();
        String Infotitle2 = infoCustom.getInfotitle2()== null ? "":infoCustom.getInfotitle2();
        String Summary = infoCustom.getSummary()== null ? "":infoCustom.getSummary();
        String Author = infoCustom.getAuthor()== null ? "":infoCustom.getAuthor();
        String Infocontent = infoCustom.getInfocontent()== null ? "":infoCustom.getInfocontent();
        String Picurl = infoCustom.getPicurl()== null ? "":infoCustom.getPicurl();
        String Returnurl = infoCustom.getReturnurl()== null ? "":infoCustom.getReturnurl();
        Date mmAddtime = infoCustom.getAddtime() == null ? new Date():infoCustom.getAddtime();
        Date mmReleasetime = infoCustom.getReleasetime() == null ? new Date("1111-11-11"):infoCustom.getReleasetime();
        Date Zhidingjieshushijian = infoCustom.getZdjssj() == null ? new Date():infoCustom.getZdjssj();
        long Shifouzhiding = infoCustom.getShifouzhiding()== null ? 0:infoCustom.getShifouzhiding();
        int Checkpass = infoCustom.getCheckpass()== null ? 0:infoCustom.getCheckpass().intValue();
        int Ordernum = infoCustom.getOrdernum()== null ? 0:Integer.parseInt(infoCustom.getOrdernum());

        if (Shifouzhiding ==1){
            int Zhidingshuliang = infoService.countZhidingxinwen(OldCategoryId);

            List<Map<String,Object>> mmList = infoService.isZhiding(InfoId);

            if (mmList.size()==0){
                if (Zhidingshuliang>=3){
                    return error("该栏目已存在三条置顶新闻，请修改置顶状态！");
                }
            }
        }
        return toAjax(infoService.modifyCustom(InfoId,OldCategoryId,Jianti,Infotitle,Infotitle2,Summary,Author,Infocontent,Picurl,Returnurl,mmAddtime,mmReleasetime,Shifouzhiding,Zhidingjieshushijian,Checkpass,Ordernum));
    }


    @Log(title = "删除新闻", businessType = BusinessType.DELETE)
    @PostMapping("/deletecustom")
    @ResponseBody
    public AjaxResult deleteCustom(@RequestParam("infoid") String InfoId,@RequestParam("categoryid") String CategoryId)
    {
        if(!IsGuanli()){
            error("当前账户非管理账户");
        }
        return toAjax(infoCategoryInfoService.deleteByInfoidAndCategoryid(InfoId,CategoryId));
    }

    @PostMapping("find_by_categoryid_paging")
    @ResponseBody
    public Map<String,Object> findByCategoryIdPaging(@RequestParam("categoryid") String ppCategoryId,@RequestParam("infotitle") String ppTitle,
                                      @RequestParam("pageindex") int ppPageIndex, @RequestParam("pagesize") int ppPageSize) {
        int mmStartIndex = (ppPageIndex - 1) * ppPageSize;
            if (!"".equals(ppTitle)){
                ppTitle = "%"+ppTitle+"%";
            }
            SysUser user = SecurityUtils.getLoginUser().getUser();
            String mmDeptId = user.getDeptId().toString();
            //String mmRoleId = user.getRoleId().toString();
            String mmUserid = user.getUserId().toString();



            if ("1".equals(mmUserid)||"2".equals(mmUserid)){
                mmDeptId = "";
            }

        System.out.println("mmDeptId:"+mmDeptId);
            int mmCount = infoService.countByCategoryIdPaging(ppCategoryId,ppTitle,mmDeptId);
            Map<String, Object> mmMap = new HashMap<String, Object>();
            PageInfo mmPageInfo = new PageInfo(ppPageIndex, ppPageSize, mmCount);
            List<Map<String, Object>> mmInfo = infoService.findByCategoryIdPaging(ppCategoryId,ppTitle,mmDeptId, mmStartIndex, ppPageSize);
            mmMap.put("InfoList", mmInfo);
            mmMap.put("PageInfo", mmPageInfo);
            return mmMap;

    }

    @PostMapping("find_by_infotitle_paging")
    @ResponseBody
    public Map<String,Object> findByInfotitlePaging(@RequestParam("infotitle") String ppTitle,
                                                     @RequestParam("pageindex") int ppPageIndex, @RequestParam("pagesize") int ppPageSize) {
        int mmStartIndex = (ppPageIndex - 1) * ppPageSize;
        if (!"".equals(ppTitle)){
            ppTitle = "%"+ppTitle+"%";
        }

        int mmCount = infoService.countPassedByCategoryIdAndTitlePaging(ppTitle);
        Map<String, Object> mmMap = new HashMap<String, Object>();
        PageInfo mmPageInfo = new PageInfo(ppPageIndex, ppPageSize, mmCount);
        List<Map<String, Object>> mmInfo = infoService.findPassedByCategoryIdAndTitlePaging(ppTitle, mmStartIndex, ppPageSize);
        mmMap.put("InfoList", mmInfo);
        mmMap.put("PageInfo", mmPageInfo);
        return mmMap;

    }

    @PostMapping("find_passed_by_categoryid_paging")
    @ResponseBody
    /*@RateLimiter(count = 150, time = 10)
    @RepeatSubmit(interval = 1000)*/
    public Map<String,Object> findPassedByCategoryIdPaging(@RequestParam("categoryid") String ppCategoryId,@RequestParam("infotitle") String ppTitle,
                                                      @RequestParam("pageindex") int ppPageIndex, @RequestParam("pagesize") int ppPageSize) {
            int mmStartIndex = (ppPageIndex - 1) * ppPageSize;
            if (!"".equals(ppTitle)){
                ppTitle = "%"+ppTitle+"%";
            }
            int mmCount = infoService.countPassedByCategoryIdPaging(ppCategoryId,ppTitle);
            Map<String, Object> mmMap = new HashMap<String, Object>();
            PageInfo mmPageInfo = new PageInfo(ppPageIndex, ppPageSize, mmCount);
            List<Map<String, Object>> mmInfo = infoService.findPassedByCategoryIdPaging(ppCategoryId,ppTitle, mmStartIndex,
                    ppPageSize);
            mmMap.put("InfoList", mmInfo);
            mmMap.put("PageInfo", mmPageInfo);
            return mmMap;

    }

    @PostMapping("find_sy_passed_by_categoryid_paging")
    @ResponseBody
    /*@RateLimiter(count = 150, time = 10)
    @RepeatSubmit(interval = 1000)*/
    public List<Map<String,Object>> findSYPassedByCategoryIdPaging(@RequestParam("categoryid") String ppCategoryId,@RequestParam("pageindex") int ppPageIndex, @RequestParam("pagesize") int ppPageSize) {
        int mmStartIndex = (ppPageIndex - 1) * ppPageSize;
        return infoService.findSYPassedByCategoryIdPaging(ppCategoryId, mmStartIndex,ppPageSize);
    }


    @PostMapping("find_passed_by_sjcategoryid")
    @ResponseBody
    /*@RateLimiter(count = 150, time = 10)
    @RepeatSubmit(interval = 1000)*/
    public List<Map<String,Object>> find_passed_by_sjcategoryid(@RequestParam("categoryid") String ppCategoryId) {

        return infoService.findPassedBySJCategoryId(ppCategoryId);
    }


    @PostMapping("find_jiansuoinfo_by_categoryid_paging")
    @ResponseBody
//    @RateLimiter(count = 100, time = 60)
//    @RepeatSubmit(interval = 1000)
    public Map<String,Object> findJiansuoInfoByCategoryIdPaging(@RequestParam("shijian") String ppShijian, @RequestParam("fanwei") String ppFanwei, @RequestParam("neirong") String ppNeirong, @RequestParam("shifouxuanzelanmu") String ppshifouxuanzelanmu, @RequestParam("categoryid") String ppCategoryid, @RequestParam("qi") String ppQi, @RequestParam("zhi") String ppZhi,
                                                                @RequestParam("paixu") String ppPaixu,@RequestParam("pageindex") int ppPageIndex, @RequestParam("pagesize") int ppPageSize) {
        int mmStartIndex = (ppPageIndex - 1) * ppPageSize;
        if (!"".equals(ppNeirong)){
            ppNeirong = "%"+ppNeirong+"%";
        }

        List<String> ppCategoryidlist = infoCategoryService.findAllXiajiCategoryid(ppCategoryid);
        int mmCount = infoService.countJiansuoInfo(ppShijian,ppFanwei,ppNeirong,ppshifouxuanzelanmu,ppCategoryidlist,ppQi,ppZhi);
        Map<String, Object> mmMap = new HashMap<String, Object>();
        PageInfo mmPageInfo = new PageInfo(ppPageIndex, ppPageSize, mmCount);
        List<Map<String, Object>> mmInfo = infoService.jiansuoInfo(ppShijian,ppFanwei,ppNeirong,ppshifouxuanzelanmu,ppCategoryidlist,ppQi,ppZhi,ppPaixu, mmStartIndex,
                ppPageSize);
        mmMap.put("InfoList", mmInfo);
        mmMap.put("PageInfo", mmPageInfo);
        return mmMap;

    }

    @PostMapping("find_passed_by_categoryid_and_deptids_paging")
    @ResponseBody
//    @RateLimiter(count = 100, time = 60)
//    @RepeatSubmit(interval = 1000)
    public Map<String,Object> findPassedByCategoryIdAndDeptidPaging(@RequestParam("categoryid") String ppCategoryId,@RequestParam("deptids") String ppDeptids,
                                                           @RequestParam("pageindex") int ppPageIndex, @RequestParam("pagesize") int ppPageSize) {
        int mmStartIndex = (ppPageIndex - 1) * ppPageSize;

        String[] deptids = ppDeptids.split(",");

        List<String> deptidList = new ArrayList<>();

        for (int i = 0; i <deptids.length; i++) {
            deptidList.add(deptids[i]);
        }

        int mmCount = infoService.countPassedByCategoryIdAndDeptIdPaging(ppCategoryId,deptidList);
        Map<String, Object> mmMap = new HashMap<String, Object>();
        PageInfo mmPageInfo = new PageInfo(ppPageIndex, ppPageSize, mmCount);
        List<Map<String, Object>> mmInfo = infoService.findPassedByCategoryIdAndDeptidPaging(ppCategoryId,deptidList, mmStartIndex,
                ppPageSize);
        mmMap.put("InfoList", mmInfo);
        mmMap.put("PageInfo", mmPageInfo);
        return mmMap;

    }

    @PostMapping("/findone")
    @ResponseBody
    @RateLimiter(count = 100, time = 60)
    @RepeatSubmit(interval = 1000)
    public Map<String, Object> findOne(@RequestParam("infoid") String infoid,@RequestParam("categoryid") String ppCategoryId)
    {
        return infoService.findOneInfo(infoid,ppCategoryId);
    }

    @Log(title = "修改新闻标题", businessType = BusinessType.UPDATE)
    @PostMapping("/modify")
    @ResponseBody
    public AjaxResult modify(@RequestParam("infoid") String infoid,@RequestParam("infotitle") String infotitle)
    {
        Info info = infoService.selectInfoByInfoid(infoid);

        info.setInfotitle(infotitle);
        return toAjax(infoService.updateInfo(info));
    }

    @PostMapping("/findxiajiallinfobycategoryid")
    @ResponseBody
    public List<Map<String, Object>> findXiajiAllInfoCategoryid(@RequestParam("categoryid") String categoryid)
    {
        List<Map<String,Object>> mmList = findAllInfoList(categoryid);
        mmList.sort(Comparator.comparing(h -> ConvertUtil.obj2String(h.get("addtime"))));
        Collections.reverse(mmList);

        return mmList;
    }

    public  List<Map<String,Object>> findAllInfoList(String categoryid){
        List<Map<String,Object>> mmInfoList = infoService.findByCategoryId(categoryid);

        List<Map<String,Object>> mmDeptList = infoCategoryService.findByParentCategoryId(categoryid);
        for (int i = 0; i < mmDeptList.size(); i++) {
            String mmCategoryid = mmDeptList.get(i).get("categoryid") == null ?"": mmDeptList.get(i).get("categoryid").toString();

            mmInfoList.addAll(infoService.findByCategoryId(mmCategoryid));

            if (infoCategoryService.findByParentCategoryId(mmCategoryid).size()>0){
                List<Map<String,Object>> mmList = findAllInfoList(mmCategoryid);
                mmInfoList.addAll(mmList);
            }
        }

        return mmInfoList;
    }

    public boolean IsGuanli(){

        /*HttpSession session = request.getSession();
        int mmIscunchu = (int)session.getAttribute("iscunchu");
        if(mmIscunchu==0){
            return false;
        }
        SessionLoginUser mmLogin = (SessionLoginUser)session.getAttribute("sessionlogin");*/

        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 获取配置文件里的用户类型
        String mmDeptId = user.getDeptId().toString();
        if("".equals(mmDeptId)) {
            return false;
        }

        //判断该用户是否是专家中心
        if(!mmDeptId.equals(RuoYiConfig.getGuanlideptid())){
            //不是上下级
            return false;
        }
        return true;
    }
}
